/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: ClientHandler.java
 * Author: ckj
 * Date: 2024/7/22 下午4:24
 * Description:
 * 
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.handle;

import com.bosssoft.constants.MessageTypeConstant;
import com.bosssoft.issue.RegisterIssue;
import com.bosssoft.issue.SpecialPathFileIssue;
import com.bosssoft.message.BaseMessage;
import com.bosssoft.message.RegisterMessage;
import com.bosssoft.message.SpecialPathFile;
import com.bosssoft.utils.ReaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

import static com.bosssoft.constants.MessageTypeConstant.SEND_FILES_TO_SPECIFIC_USERS;


/**
 * @author ckj
 */
public class ClientHandler implements Runnable{

    private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class);
    private final Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true)
        ){
            handleMessage(reader, writer);
        } catch (Exception e) {
            logger.error("用户下线");

        }
    }
    /**
     *
     * @author ckj
     * @date 2024/07/22 下午10:39
     * 不断接收和处理来自客户端的消息，根据消息类型执行相应的处理逻辑，并在出现异常时进行适当的清理和日志记录。
     * @return void
     */
    public void handleMessage(BufferedReader reader,PrintWriter writer) {
        while ( true ){
            try {
                if ( "Start".equals(reader.readLine())){
                    String typeString = ReaderUtil.readLineWithAes(reader);
                    int type = Integer.parseInt(typeString);
                    if(type == MessageTypeConstant.REGISTERED_MESSAGE){
                        BaseMessage message = new RegisterMessage().parse(reader, type);
                        RegisterIssue registerIssue = new RegisterIssue(socket, writer, message);
                        new RegisterHandle().handle(registerIssue);
                    } else if (type == SEND_FILES_TO_SPECIFIC_USERS){
                        BaseMessage message = new SpecialPathFile().parse(reader, type);
                        SpecialPathFileIssue specialPathFileIssue = new SpecialPathFileIssue(message,writer);
                        new SpecialPathFileHandle().handle(specialPathFileIssue);
                    }
                }
            } catch (Exception e) {
                logger.info("用户退出");
                return;
            }
        }
    }
}
